package pa165.dominatingspecies.frontend.user;

import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.StringResourceModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.springframework.dao.DataAccessException;
import pa165.dominating.species.enums.UserType;
import pa165.dominating.species.service.UserService;
import pa165.dominating.species.tos.UserTO;
import pa165.dominatingspecies.frontend.element.EnumDropDown;
import pa165.dominatingspecies.frontend.pages.BasePage;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.wicket.model.PropertyModel;
import org.springframework.security.access.prepost.PreAuthorize;

/**
 * @author Tomas Kalla
 */
@PreAuthorize("hasRole('ADMIN')")
public class EditUserPage extends BasePage {

    @SpringBean(name = "userService")
    private UserService userService;
    private UserTO userTO;
    private String userPsswd;
    private List<UserType> selected = new ArrayList();

    public EditUserPage(Long id) {
        if (id != null) {
            userTO = userService.getUserById(id);
            userPsswd = userTO.getPassword();
            userTO.setPassword(null);

        }

        Form<UserTO> form = new Form<>("createUserForm");
        form.setModel(new CompoundPropertyModel<>(userTO));
        form.add(new Label("nameLabel", new StringResourceModel("uName", this, null)));
        form.add(new TextField<String>("name"));
        form.add(new Label("usernameLabel", new StringResourceModel("uLogin", this, null)));
        form.add(new TextField<String>("login"));
        form.add(new Label("passwordLabel", new StringResourceModel("uPassword", this, null)));
        TextField<String> psswd = new TextField<String>("password");
        psswd.clearInput();
        form.add(psswd);
        form.add(new Label("userType", new StringResourceModel("uUserType", this, null)));
        form.add(new EnumDropDown<>("type", new PropertyModel<UserType>(userTO, "type")));
        form.add(new UserPageLink("goBack"));

        Button submitButton = new Button("submitButton") {
            @Override
            public void onSubmit() {
                boolean errorsFound = false;
                if (userTO.getName() == null) {
                    getSession().warn(new StringResourceModel("userNameEmptyWarn", this, null).getString());
                    errorsFound = true;
                }
                if (userTO.getLogin() == null) {
                    getSession().warn(new StringResourceModel("userLoginEmptyWarn", this, null).getString());
                    errorsFound = true;
                }
                if (userTO.getType() == null) {
                    getSession().warn(new StringResourceModel("userTypeEmptyWarn", this, null).getString());
                    errorsFound = true;
                }

                if (userTO.getPassword() == null) {
                    userTO.setPassword(userPsswd);
                    //getSession().warn(new StringResourceModel("userPasswordEmptyWarn", this, null).getString());
                    //errorsFound = true;
                }
                
                if(userTO.getPassword() != null){
                   userTO.setPassword(DigestUtils.shaHex(userTO.getPassword()));
                }

                if (!errorsFound) {
                    boolean thrown = false;
                    try {
                        userService.updateUser(userTO);
                    } catch (DataAccessException ex) {
                        getSession().warn(new StringResourceModel("userUpdateFail", this, null, new Object[]{userTO.getId().toString(), userTO.getLogin().toString()}).getString());
                        thrown = true;
                    } catch (Exception ex) {
                        Logger.getLogger(EditUserPage.class.getName()).log(Level.SEVERE, null, ex);
                    }

                    if (!thrown) {
                        getSession().info(new StringResourceModel("userUpdateSucc", this, null, new Object[]{userTO.getId()}).getString());
                        setResponsePage(UserPage.class);
                    }
                }
            }
        };
        form.add(submitButton);
        add(form);
    }
}
